#!/bin/bash

local_branch=$(git symbolic-ref HEAD)
remote_branch=$(git for-each-ref --format='%(upstream:short)' "${local_branch}")

# Don't push origin/devlop or origin/phasexx/current directly
if [[ "${remote_branch}" =~ ^origin/(develop|phase[0-9]+/current)$ ]]; then
    echo -e "\e[31merror: Directly push ${BASH_REMATCH[0]} is prohibited, create your own branch instead\e[0m"
    exit 1 # Non-zero to abort push
fi

# Define the prohibited push time periods (00:00:00 - 15:00:00)
SH=00 SM=00 SS=00 EH=15 EM=00 ES=00
START_TIME=$((10#$SH * 3600 + 10#$SM * 60 + 10#$SS)) # in seconds
END_TIME=$((10#$EH * 3600 + 10#$EM * 60 + 10#$ES))   # in seconds

# Define the prohibited push weekdays (Tuesday and Thursday)
NOT_ALLOWED_DAYS=(2 4) # day of week (1..7); 1 is Monday
NOT_ALLOWED_DAYS_LOCALE=() # DO NOT modify me, modify NOT_ALLOWED_DAYS instead
if [ "${SHELL:0-4}" = .exe ]; then
    # This is a workaround:
    # In Windows git bash env, it's miserable to touch locale stuff.. e.g. GBK -> UTF-8,
    # so NOT_ALLOWED_DAYS_LOCALE is simply the same as NOT_ALLOWED_DAYS
    IN_WIN_GITBASH=1
    NOT_ALLOWED_DAYS_LOCALE+=(Day)
fi
for day in "${NOT_ALLOWED_DAYS[@]}"
do
    if [ "${IN_WIN_GITBASH}" = 1 ]; then
        NOT_ALLOWED_DAYS_LOCALE+=("${day}")
    else
        NOT_ALLOWED_DAYS_LOCALE+=($(date -d "last-sunday +${day} day" +%a))
    fi
done

# Get current weekday and time
current_day=$(date +%u)    # day of week (1..7); 1 is Monday
current_hour=$(date +%H)   # 00..23
current_minute=$(date +%M) # 00..59
current_second=$(date +%S) # 00..60

# Convert current time to seconds（10# to prevent leading zero number being interpreted as octal）
current_time=$((10#${current_hour} * 3600 + 10#${current_minute} * 60 + 10#${current_second}))

if [[ "${NOT_ALLOWED_DAYS[*]}" =~ ${current_day} && "${current_time}" -gt "${START_TIME}" &&\
      "${current_time}" -lt "${END_TIME}" && "${remote_branch}" =~ ^origin/.+[-_]phase[0-9]+$ ]]; then
    if [[ -n "${force_push}" && "${force_push}" == 1 ]]; then
        echo -e "\e[33mwarning: force_push = 1\e[0m"
    else
        echo -e "\e[31merror：try to push ${remote_branch} in restricted time (${NOT_ALLOWED_DAYS_LOCALE[*]} $SH:$SM:$SS-$EH:$EM:$ES)\e[0m"
        exit 1 # Non-zero to abort push
    fi
fi

# Uncomment to test the script
#echo "TEST: exit 1" && exit 1